package com.future.common.security.service;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;

import com.future.common.api.auth.StatusUser;
import com.future.common.api.auth.SysUser;
import com.future.common.api.auth.UserInfo;
import com.future.common.api.content.CacheConstants;
import com.future.common.api.content.CommonConstants;
import com.future.common.api.content.SecurityConstant;
import com.future.common.api.feign.RemoteUserService;
import com.future.common.api.result.R;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @ClassName : StatusUserDetailsServiceImpl
 * @Author : lby
 * @Date: 2021/5/6 21:52
 * @Description :
 */
@Slf4j
@AllArgsConstructor
@Service
public class StatusUserDetailsServiceImpl implements StatusDetailService {
    private final RemoteUserService remoteUserService;
    private final CacheManager cacheManager;

    /**
     * 用户密码登录
     *
     * @param username 用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    @SneakyThrows
    public UserDetails loadUserByUsername(String username) {
//        Cache cache = cacheManager.getCache(CacheConstants.GLOBALLY + CacheConstants.USER_DETAILS);
//        if (cache != null && cache.get(username) != null) {
//            return (StatusUser) cache.get(username).get();
//        }

        R<UserInfo> loginUser = remoteUserService.getLoginUser(username, SecurityConstant.FROM_IN);

        UserDetails userDetails = getUserDetails(loginUser);
//        cache.put(username, userDetails);
        return userDetails;
    }


    /**
     * 根据社交登录code 登录
     *
     * @param inStr TYPE@CODE
     * @return UserDetails
     * @throws UsernameNotFoundException
     */
    @Override
    @SneakyThrows
    public UserDetails loadUserBySocial(String inStr) {
        return null;
//        return getUserDetails(remoteUserService.social(inStr, SecurityConstant.FROM_IN));
    }

    /**
     * 构建userdetails
     *
     * @param result 用户信息
     * @return
     */
    private UserDetails getUserDetails(R<UserInfo> result) {
        if (result == null || result.getData() == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        UserInfo info = result.getData();
        Set<String> dbAuthsSet = new HashSet<>();
        if (ArrayUtil.isNotEmpty(info.getRoles())) {
            // 获取角色
            Arrays.stream(info.getRoles()).forEach(roleId -> dbAuthsSet.add(SecurityConstant.ROLE + roleId));
            // 获取资源
            dbAuthsSet.addAll(Arrays.asList(info.getPermissions()));
        }
        Collection<? extends GrantedAuthority> authorities
                = AuthorityUtils.createAuthorityList(dbAuthsSet.toArray(new String[0]));
        SysUser user = info.getSysUser();
        //当用户为空认为是扫码登录，构造虚拟用户
        if (user == null || user.getUserId() == null) {
            if (user == null) {
                user = new SysUser();
            }
            user.setUsername(UUID.randomUUID().toString());
            user.setPassword("123456");
            user.setLockFlag(CommonConstants.STATUS_NORMAL);
        }
        boolean enabled = StrUtil.equals(user.getLockFlag(), CommonConstants.STATUS_NORMAL);
        // 构造security用户
        return new StatusUser(user.getUserId(), user.getDeptId(), 0, user.getUsername(), SecurityConstant.BCRYPT + user.getPassword(), enabled,
                true, true, !CommonConstants.STATUS_LOCK.equals(user.getLockFlag()), authorities, user);
    }


}
